package Eyjafjalla.modcore;

import Eyjafjalla.card.AbstractEyjafjallaCard;
import Eyjafjalla.character.Eyjafjalla;
import Eyjafjalla.helper.EyjafjallaHelper;
import Eyjafjalla.helper.ImageHelper;
import Eyjafjalla.helper.ModConfig;
import Eyjafjalla.helper.StringHelper;
import Eyjafjalla.patch.*;
import Eyjafjalla.power.FireMarkPower;
import basemod.BaseMod;
import basemod.helpers.RelicType;
import basemod.interfaces.*;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.evacipated.cardcrawl.modthespire.lib.SpireConfig;
import com.evacipated.cardcrawl.modthespire.lib.SpireInitializer;
import com.google.gson.Gson;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.helpers.CardLibrary;
import com.megacrit.cardcrawl.localization.*;
import com.megacrit.cardcrawl.powers.AbstractPower;
import com.megacrit.cardcrawl.relics.AbstractRelic;
import com.megacrit.cardcrawl.rooms.AbstractRoom;
import com.megacrit.cardcrawl.unlock.UnlockTracker;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Properties;

@SpireInitializer
public class EyjafjallaMod implements OnPlayerTurnStartSubscriber,PostUpdateSubscriber,EditCharactersSubscriber, EditCardsSubscriber, EditRelicsSubscriber, EditKeywordsSubscriber, EditStringsSubscriber,PostInitializeSubscriber,OnStartBattleSubscriber,PreStartGameSubscriber,PostBattleSubscriber {

    private static final Logger logger = LogManager.getLogger(EyjafjallaMod.class);

    public static final Color mColor = new Color(170f/255f,141f/255f,127f/255f,1f);

    public static final String cardBg512 = "EyjafjallaResources/img/512/cardbg.png";
    public static final String cardBgD512 = "EyjafjallaResources/img/512/cardbgD.png";
    public static final String energy512 = "EyjafjallaResources/img/512/energybg.png";
    public static final String cardBg1024 = "EyjafjallaResources/img/1024/cardbg.png";
    public static final String cardBgD1024 = "EyjafjallaResources/img/1024/cardbgD.png";
    public static final String energy1024 = "EyjafjallaResources/img/1024/energybg.png";

    public static int DefaultSkinIndex;

    public static void initialize(){
        new EyjafjallaMod();

        try{
            Properties defaults = new Properties();
            defaults.setProperty("defaultSkin","0");
            SpireConfig config = new SpireConfig("Eyjafjalla_FimmlpS","Common",defaults);
            DefaultSkinIndex = config.getInt("defaultSkin");

        }catch (IOException var1){
            var1.printStackTrace();
        }
    }

    public static void logSomething(String mes){
        logger.info(mes);
    }

    public EyjafjallaMod(){
        BaseMod.subscribe(this);
        BaseMod.addColor(ColorEnum.Eyjafjalla_COLOR,mColor.cpy(),mColor.cpy(),mColor.cpy(),mColor.cpy(),mColor.cpy(),mColor.cpy(),mColor.cpy(),cardBg512,cardBg512,cardBg512,energy512,cardBg1024,cardBg1024,cardBg1024,energy1024,"EyjafjallaResources/img/orbs/EnergyOrb.png");
        BaseMod.addColor(ColorEnum.Eyjafjalla_Dolly_COLOR,mColor.cpy(),mColor.cpy(),mColor.cpy(),mColor.cpy(),mColor.cpy(),mColor.cpy(),mColor.cpy(),cardBgD512,cardBgD512,cardBgD512,energy512,cardBgD1024,cardBgD1024,cardBgD1024,energy1024,"EyjafjallaResources/img/orbs/EnergyOrb.png");
        ModConfig.initModSettings();
    }

    @Override
    public void receiveEditCharacters() {
        BaseMod.addCharacter(new Eyjafjalla("Eyjafjalla"),
                "EyjafjallaResources/img/charSelect/EyjafjallaButton.png",
                "EyjafjallaResources/img/charSelect/EyjafjallaBG.png",
                ClassEnum.Eyjafjalla_CLASS);
    }

    @Override
    public void receiveEditCards() {
        BaseMod.addDynamicVariable(new AbstractEyjafjallaCard.FireNumber());
        Iterator<AbstractCard> var1 = StringHelper.getCardsToAdd().iterator();
        while (var1.hasNext()){
            AbstractCard c = var1.next();
            BaseMod.addCard(c);
        }

        var1 = StringHelper.getDollyCardsToAdd().iterator();
        while (var1.hasNext()){
            AbstractCard c = var1.next();
            BaseMod.addCard(c);
        }
    }

    @Override
    public void receiveEditRelics() {
        for(AbstractRelic r:StringHelper.getRelicsToAdd(true)){
            BaseMod.addRelicToCustomPool(r,ColorEnum.Eyjafjalla_COLOR);
        }

        for(AbstractRelic r:StringHelper.getRelicsToAdd(false)){
            BaseMod.addRelic(r, RelicType.SHARED);
        }
    }

    @Override
    public void receiveOnBattleStart(AbstractRoom abstractRoom) {
        HeartPatch.AlwaysHeart = false;
        CloudFixPatch.canSetRoundEnd = false;
        //重置浅海轻唱
        EyjafjallaHelper.initMelodies();
    }

    @Override
    public void receivePreStartGame() {
        CloudPatch.clearCloud();
        HeartPatch.AlwaysHeart = false;
        CloudFixPatch.canSetRoundEnd = false;
        MelodyPatch.clear();
    }

    @Override
    public void receivePostBattle(AbstractRoom abstractRoom) {
        CloudPatch.clearCloud();
        HeartPatch.AlwaysHeart = false;
        CloudFixPatch.canSetRoundEnd = false;
        MelodyPatch.clear();
    }

    @Override
    public void receiveOnPlayerTurnStart() {
        CloudFixPatch.turnClear();
    }

    @Override
    public void receivePostUpdate() {
        if(AbstractDungeon.player!=null){
            AbstractPower p = AbstractDungeon.player.getPower(FireMarkPower.POWER_ID);
            if(p!=null&&p.amount!=0){
                FirePatch.hasFireMark = true;
                FirePatch.fireMarkAmount = p.amount;
                return;
            }
        }
        FirePatch.hasFireMark = false;
        FirePatch.fireMarkAmount = 0;
    }

    @Override
    public void receiveEditKeywords() {
        Gson gson = new Gson();
        String lang = "en";
        if (Settings.language == Settings.GameLanguage.ZHS || Settings.language == Settings.GameLanguage.ZHT) {
            lang = "zh";
            FirePatch.unChinese = false;
        } else {
            lang = "en";
            FirePatch.unChinese = true;
        }

        String json = Gdx.files.internal("EyjafjallaResources/localization/ThMod_Eyjafjalla_keywords-"+lang+".json").readString(String.valueOf(StandardCharsets.UTF_8));
        Keyword[] keywords = (Keyword[])gson.fromJson(json, Keyword[].class);
        if (keywords != null) {
            Keyword[] var5 = keywords;
            int var6 = keywords.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                Keyword keyword = var5[var7];
                BaseMod.addKeyword("eyjafjalla", keyword.NAMES[0], keyword.NAMES, keyword.DESCRIPTION);
            }
        }
    }

    @Override
    public void receiveEditStrings() {
        String relic = "",card = "",power= "",potion="",event="",character="",ui="",monster="";
        String fore = "EyjafjallaResources/localization/";
        String mid = "/ThMod_Eyjafjalla_";
        String lang = "zh";
        String back = ".json";
        if (Settings.language == Settings.GameLanguage.ZHS||Settings.language==Settings.GameLanguage.ZHT) {
            lang = "zh";
        } else {
            //其他语言配置的JSON
            lang = "en";
        }

        card = fore+lang+mid+"cards-"+lang+back;
        relic = fore+lang+mid+"relics-"+lang+back;
        power = fore+lang+mid+"powers-"+lang+back;
        event = fore+lang+mid+"events-"+lang+back;
        character = fore+lang+mid+"characters-"+lang+back;
        ui = fore+lang+mid+"uis-"+lang+back;
        monster = fore+lang+mid+"monsters-"+lang+back;

        String relicStrings = Gdx.files.internal(relic).readString(String.valueOf(StandardCharsets.UTF_8));
        BaseMod.loadCustomStrings(RelicStrings.class, relicStrings);
        String cardStrings = Gdx.files.internal(card).readString(String.valueOf(StandardCharsets.UTF_8));
        BaseMod.loadCustomStrings(CardStrings.class, cardStrings);
        String powerStrings = Gdx.files.internal(power).readString(String.valueOf(StandardCharsets.UTF_8));
        BaseMod.loadCustomStrings(PowerStrings.class, powerStrings);
        String eventStrings = Gdx.files.internal(event).readString(String.valueOf(StandardCharsets.UTF_8));
        BaseMod.loadCustomStrings(EventStrings.class,eventStrings);
        String characterStrings = Gdx.files.internal(character).readString(String.valueOf(StandardCharsets.UTF_8));
        BaseMod.loadCustomStrings(CharacterStrings.class,characterStrings);
        String uiStrings = Gdx.files.internal(ui).readString(String.valueOf(StandardCharsets.UTF_8));
        BaseMod.loadCustomStrings(UIStrings.class,uiStrings);
        String monsterStrings = Gdx.files.internal(monster).readString(String.valueOf(StandardCharsets.UTF_8));
        BaseMod.loadCustomStrings(MonsterStrings.class,monsterStrings);
    }

    private static void unlockCards(){
        Iterator<AbstractCard> var1 = StringHelper.getCardsToAdd().iterator();
        while (var1.hasNext()){
            AbstractCard c = var1.next();
            String key = c.cardID;
            AbstractCard tmp = CardLibrary.getCard(key);
            if (tmp != null && !CardLibrary.getCard(key).isSeen) {
                tmp.isSeen = true;
                tmp.unlock();
                UnlockTracker.seenPref.putInteger(key, 1);
            }
        }
        var1 = StringHelper.getDollyCardsToAdd().iterator();
        while (var1.hasNext()){
            AbstractCard c = var1.next();
            String key = c.cardID;
            AbstractCard tmp = CardLibrary.getCard(key);
            if (tmp != null && !CardLibrary.getCard(key).isSeen) {
                tmp.isSeen = true;
                tmp.unlock();
                UnlockTracker.seenPref.putInteger(key, 1);
            }
        }
        UnlockTracker.seenPref.flush();
    }

    private static void unlockRelics(){
        for(AbstractRelic r:StringHelper.getRelicsToAdd(true)){
            UnlockTracker.markRelicAsSeen(r.relicId);
        }

        for(AbstractRelic r:StringHelper.getRelicsToAdd(false)){
            UnlockTracker.markRelicAsSeen(r.relicId);
        }
    }

    @Override
    public void receivePostInitialize() {
        StringHelper.initializeMonsters();
        StringHelper.initializeEvents();
        unlockCards();
        unlockRelics();
        ModConfig.initModConfigMenu();
        ImageHelper.initThis();
    }
}
